'use client';

import React, { useState, useEffect, use } from "react";
import styles from "./page.module.css";
import Image from "next/image";
import { notFound } from "next/navigation";

// 服务器端获取文章数据
async function getServerPostData(id) {
  // 拼接完整 URL（开发环境用 localhost:3000，生产环境替换为实际域名）
  const baseUrl = process.env.NODE_ENV === 'development'
    ? 'http://localhost:3000'
    : 'https://你的生产环境域名';
  const res = await fetch(`${baseUrl}/api/posts/${id}`, {
    method: "GET",
    headers: { "Content-Type": "application/json" },
    cache: "no-store",
  });

  if (!res.ok) {
    return notFound();
  }

  return res.json();
}

const BlogPost = ({ params }) => {
  // 解析 params 获取 id
  const { id } = use(params);

  const [post, setPost] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  // 初始化数据
  useEffect(() => {
    const loadData = async () => {
      try {
        const data = await getServerPostData(id);
        setPost(data);
      } catch (err) {
        console.error("加载文章失败:", err);
      } finally {
        setIsLoading(false);
      }
    };

    loadData();
  }, [id]);

  if (isLoading) return <div className={styles.loading}>加载中...</div>;
  if (!post) return <div className={styles.error}>文章不存在</div>;

  return (
    <div className={styles.container}>
      <div className={styles.top}>
        {/* 左侧内容区：标题、作者、正文 */}
        <div className={styles.leftContent}>
          <div className={styles.info}>
            <h1 className={styles.title}>{post.title}</h1>
            <p className={styles.desc}>{post.desc}</p>
            <div className={styles.author}>
              <Image
                src={post.authorAvatar || "/contact.png"}
                alt={post.username}
                width={40}
                height={40}
                className={styles.avatar}
              />
              <span className={styles.username}>{post.username}</span>
            </div>
          </div>

          {/* 内容区域移至作者信息下方 */}
          <div className={styles.content}>
            <p className={styles.text}>{post.content}</p>
          </div>
        </div>

        {/* 右侧图片区 */}
        <div className={styles.imageContainer}>
          <Image
            src={post.img}
            alt={post.title}
            fill={true}
            className={styles.image}
            sizes="(max-width: 768px) 100vw, 40vw"
          />
        </div>
      </div>
    </div>
  );
};

export default BlogPost;